<template>
    <div focusable="false" class="container">
        <div
            class="defalut-focux"
            ref="defalutFocusRef"
            :focusable="defalutFocusStatus"
            requestFocus="true"
            @focus="() => defalutFocusSelect()"
            @click="() => defalutFocusClick()"
            nextFocusName="{msgId:'defalutFocus', left:'self',down:'self',up:'self',right:'self'}"
        ></div>

        <div
            class="wrap"
            :style="isFlow ? { top: `${topSpace}px` } : null"
            ref="containerRef"
        >
            <div
                class="left-bg-image"
                v-if="startAnimation"
                ref="leftBgImage"
            ></div>
            <div
                class="right-bg-image"
                v-if="startAnimation"
                ref="rightBgImage"
            ></div>
            <div class="center-bg-image"></div>
            <Home
                v-if="configInited"
                ref="homeWrap"
                :route="route"
                :entryPage="entryPage"
                :allConfig="allConfig"
                :focusHistoryRef="focusHistoryRef"
                :lastFocusHistoryRef="lastFocusHistoryRef"
                @focusHistoryChange="focusHistoryChange"
                @enterFullScreenAction="enterFullScreenAction"
                @goRouterLink="goRouterLink"
                @onFocusNavTab="handleFocusNavTab"
                :animationDone="startAnimationDone"
            />
        </div>
    </div>
</template>
<script>
import atlas from "@/atlas";
import Store from "@/store";
import API from "@/server";
import Vue from "vue";
import Home from "@/page/home/index.vue";
import CONFIG from "@/assets/raw/config.js";
export default {
    name: "index",
    components: {
        Home,
    },
    data() {
        return {
            // 弹框时记录当前焦点位置
            focusHistoryRef: "HeaderBannerWrap",
            // 原始焦点位置
            oldFocusHistoryRef: "HeaderBannerWrap",
            // 上一个焦点文字
            lastFocusHistoryRef: "HeaderBannerWrap",
            // 配置是否加载完成
            configInited: false,
            // 是否正在重新加载页面，控制多次快速操作返回键直接跳出少儿
            isRouterLoading: false,
            // 接收参数
            entryPage: null,
            // 配置信息
            allConfig: null,
            // 当前路由信息
            route: {
                name: "home",
                data: {},
                focusInfo: null, // 焦点信息，跳转前设置，用户恢复焦点
            },
            // tab切换下标
            bannerFocusIndex: 0,
            // 优惠券信息
            newCouponList: [],
            // 默认焦点是否打开
            defalutFocusStatus: false,
            // 焦点禁用清除
            defalutFocusTime: null,
            // 是否缓存快应用状态
            isNotVisibleToUser: false,
            // 开始左右两侧动画标识位
            startAnimation: false,
            // 左右两侧动画结束
            startAnimationDone: false,
            // 顶部距离
            topSpace: CONFIG.TOP_SPACE,
        };
    },
    created() {
        // 获取ms缓存
        Store.init(() => {
            // Vue.Native.callNative(
            //     "ConsoleModule",
            //     "log",
            //     `routerToPage=>index:init`
            // );
            this.init();
        });
    },
    mounted() {
        // Vue.Native.callNative(
        //     "ConsoleModule",
        //     "log",
        //     `routerToPage=>index:mounted`
        // );
        this.onEvent();
        // 全屏播放器播放结束
        Store.on("goRouterLink", (name) => {
            this.goRouterLink(name);
        });
    },
    computed: {
        // 是否挂载瀑布流上加载
        isFlow() {
            return this.entryPage?.flowType === "QUICK_APP";
        },
    },
    beforeDestroy() {
        console.log("beforeDestroy:page=>index");
        this.offEvent();
    },
    methods: {
        // 初始化获取配置信息
        init() {
            API.getAllConfig(() => {
                const CONFIG = Store.getData("allConfigs");
                const doLog = CONFIG?.doLog;
                if (!__IS_DEV__ && doLog) {
                    // if (doLog) {
                    console.log = (...args) => {
                        Vue.Native.callNative(
                            "ConsoleModule",
                            "log",
                            args.join(",")
                        );
                    };
                }
                this.allConfig = CONFIG;
                this.configInited = true;
                // 获取进入项目携带的参数
                this.getEntryParams();
            });
        },
        // 获取参数信息
        getEntryParams() {
            // let entryPage =
            //     '{"psId":"3192007","desktopId":"1397102618861371392","url":"detail","isDebugMode":false}';
            let { entryPage } = this.app.$options.$superProps;
            // console.log(
            //     "getEntryParams:entryPage1",
            //     JSON.stringify(entryPage),
            //     typeof entryPage
            // );
            if (entryPage) {
                try {
                    entryPage = JSON.parse(entryPage);
                    if (__IS_DEV__) {
                        entryPage = {
                            title: "周边生活快应用",
                            url: "home",
                        };
                    }
                    // 首次曝光的from
                    if (!entryPage.pageFrom) {
                        entryPage.pageFrom = entryPage?.flowId || "999";
                    }
                    let dataInfo = {
                        ...entryPage,
                    };
                    // 获取参数后设置初始路由
                    let urlString = entryPage.url || "home";
                    if (urlString === "/home") {
                        urlString = "home";
                    }
                    entryPage.url = urlString;
                    this.entryPage = entryPage;
                    // console.log(
                    //     "getEntryParams:entryPage2",
                    //     JSON.stringify(entryPage)
                    // );
                    Store.setData("entryPage", entryPage);
                    this.$nextTick(() => {
                        this.route = {
                            name: urlString,
                            leaveName: urlString,
                            data: dataInfo,
                            focusInfo: null,
                        };
                        setTimeout(
                            () => {
                                // 取消加载中页面展示
                                atlas.completeLoad();
                                atlas.notifyMount();
                            },
                            this.isFlow ? 400 : 200
                        );
                        if (!this.isFlow) {
                            // 设置进入周边生活为是
                            atlas
                                .fetchDataInfo(
                                    "data",
                                    "{'type':'memory','key':'LAUNCHER_TO_AROUND_LIFE'}",
                                    "1"
                                )
                                .then((res) => {
                                    console.log(
                                        "LAUNCHER_TO_AROUND_LIFE1",
                                        res
                                    );
                                });
                        }
                        // 开始执行动画
                        this.startAnimationAction();
                    });
                } catch (e) {
                    console.log("home entryPage parse error", e);
                }
            }
        },
        // 绑定事件
        onEvent() {
            this.app.$on("LifecycleChange", this.lifecycleChange);
        },
        // 绑定事件
        offEvent() {
            this.app.$off("LifecycleChange", this.lifecycleChange);
        },
        // 跳转页面或打开弹框
        goRouterLink(name) {
            this.oldFocusHistoryRef = this.focusHistoryRef;
            if (this.defalutFocusTime) {
                clearTimeout(this.defalutFocusTime);
                this.defalutFocusTime = null;
            }
            this.defalutFocusStatus = true;
            this.route.name = name;
        },
        // 页面监听
        lifecycleChange(evt) {
            console.log(
                "LifecycleChange:====index",
                evt,
                this.isNotVisibleToUser
            );
            // 【注意】调用LifecycleChange，销毁或注册全局投屏和语音方法；
            // 暂停时销毁全局投屏和语音
            if (evt === "onPause" || evt === "isNotVisibleToUser") {
                if (evt === "isNotVisibleToUser") {
                    this.isNotVisibleToUser = true;
                    this.handleFocusNavTab();
                    // 设置进入周边生活为否
                    atlas
                        .fetchDataInfo(
                            "data",
                            "{'type':'memory','key':'LAUNCHER_TO_AROUND_LIFE'}",
                            "0"
                        )
                        .then((res) => {
                            console.log("LAUNCHER_TO_AROUND_LIFE2", res);
                        });
                }
            } else if (evt === "isVisibleToUser" && this.isNotVisibleToUser) {
                // 设置进入周边生活为是
                atlas
                    .fetchDataInfo(
                        "data",
                        "{'type':'memory','key':'LAUNCHER_TO_AROUND_LIFE'}",
                        "1"
                    )
                    .then((res) => {
                        console.log("LAUNCHER_TO_AROUND_LIFE3", res);
                    });
            }
        },
        // 上焦历史信息
        focusHistoryChange(ref) {
            console.log("focusHistoryChange", ref);
            if (ref) {
                this.lastFocusHistoryRef = this.focusHistoryRef;
            }
            this.focusHistoryRef = ref ? ref : this.oldFocusHistoryRef;
        },
        // 默认焦点
        defalutFocusSelect() {
            console.log("defalutFocusSelect");
        },
        // 默认焦点
        defalutFocusClick() {},
        // 上焦到flow
        handleFocusNavTab() {
            // if (!this.isFlow) {
            //     this.startAnimation = false;
            //     this.startAnimationDone = false;
            //     this.$refs?.homeWrap?.resetCompSetFocus(0);
            // }
            if (CONFIG.FULL_SCREEN_ANI) {
                atlas.doAnimation(this.$refs.containerRef, "homeUp", [
                    {
                        translationY: {
                            start: -140,
                            end: 0,
                            timingFunction: "ease-in",
                        },
                        duration: 300,
                    },
                ]);
            } else {
                this.topSpace += 140;
            }
            if (this.route.name === "home") {
                this.$refs?.homeWrap?.handleFocusNavTab();
            } else {
                this.goBackHome();
            }
        },
        // 关闭导航并上焦到当前页面
        enterFullScreenAction() {
            console.log("enterFullScreenAction:action", CONFIG.FULL_SCREEN_ANI);
            atlas.onLauncherCall("enterFullScreen");
            if (CONFIG.FULL_SCREEN_ANI) {
                atlas.doAnimation(this.$refs.containerRef, "homeUp", [
                    {
                        translationY: {
                            start: 0,
                            end: -140,
                            timingFunction: "ease-in",
                        },
                        duration: 300,
                    },
                ]);
            } else {
                this.topSpace -= 140;
            }
            console.log(
                "enterFullScreenAction:this.isNotVisibleToUser",
                this.isNotVisibleToUser
            );
            // 存在缓存,重新注册监听
            if (this.isNotVisibleToUser) {
                this.isNotVisibleToUser = false;
            }
            console.log(
                "enterFullScreenAction:this.route.name",
                this.route.name
            );
            if (this.route.name === "home") {
                console.log(
                    "enterFullScreenAction:this.$refs?.homeWrap",
                    this.$refs?.homeWrap
                );
                // 上焦到banner
                this.$refs?.homeWrap?.resetCompSetFocus();
                this.$refs?.homeWrap?.offEvent();
                this.$refs?.homeWrap?.onEvent();
            } else if (this.$refs[`${this.route.name}Wrap`]) {
                this.$refs[`${this.route.name}Wrap`]?.compSetFocus();
            }
        },
        // 跳转返回主页
        goBackHome() {
            // 日程页面返回，刷新数据
            const oldRouteName = this.route.name;
            this.route.name = "home";
            this.$refs?.homeWrap?.resetFocusAction(oldRouteName);
            this.$nextTick(() => {
                this.defalutFocusTime = setTimeout(() => {
                    this.defalutFocusStatus = false;
                }, 500);
            });
        },
        /**
         * 开始执行动画
         * @param {*}
         * data：2024/07/19
         * author: wzl
         */
        startAnimationAction() {
            console.log("startAnimationAction", CONFIG.DONGTAI_TIMOUT);
            if (this.isFlow) {
                this.startAnimation = true;
                this.startAnimationDone = true;
                return;
            }
            setTimeout(() => {
                if (CONFIG.ENTER_ANI) {
                    setTimeout(() => {
                        this.startAnimation = true;
                        this.$nextTick(() => {
                            setTimeout(() => {
                                this.startAnimationDone = true;
                            }, 1e3);
                            atlas.doAnimation(
                                this.$refs.leftBgImage,
                                "leftTrans",
                                [
                                    {
                                        translationX: {
                                            start: -500,
                                            end: 0,
                                            timingFunction: "ease-in",
                                        },
                                        duration: 300,
                                    },
                                ]
                            );
                            atlas.doAnimation(
                                this.$refs.rightBgImage,
                                "rightTrans",
                                [
                                    {
                                        translationX: {
                                            start: 500,
                                            end: 0,
                                            timingFunction: "ease-in",
                                        },
                                        duration: 300,
                                    },
                                ]
                            );
                        });
                    }, 100);
                } else {
                    this.startAnimation = true;
                    this.startAnimationDone = true;
                }
            }, CONFIG.DONGTAI_TIMOUT);
        },
    },
    watch: {
        // tab切换刷新日程数据
        "route.name"(newValue, oldValue) {
            if (newValue !== oldValue) {
                if (newValue === "home") {
                    this.$refs?.homeWrap?.onEvent();
                } else if (oldValue === "home") {
                    this.$refs?.homeWrap?.offEvent();
                }
            }
        },
    },
};
</script>
<style lang="less" scoped>
.container {
    width: 1920px;
    height: 1080px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    background-image: url(assets/raw/image/global-bg.webp);
    background-size: 100% 100%;
    .wrap {
        width: 1920px;
        height: 1080px;
        background-color: transparent;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2000;
    }
}
.left-bg-image {
    position: absolute;
    left: 75px;
    top: 60px;
    width: 345px;
    height: 960px;
    background-image: url(assets/raw/image/global-bg-left-block.webp);
    background-size: 100% 100%;
    z-index: -1;
}
.right-bg-image {
    position: absolute;
    right: 75px;
    top: 60px;
    width: 345px;
    height: 960px;
    background-image: url(assets/raw/image/global-bg-right-block.webp);
    background-size: 100% 100%;
    z-index: -1;
}
.center-bg-image {
    position: absolute;
    left: 450px;
    top: 60px;
    width: 1020px;
    height: 960px;
    background-image: url(assets/raw/image/global-bg-center-block.webp);
    background-size: 100% 100%;
    z-index: -1;
}
</style>
